module DLL_design (
    input clk,
    input rst_n,

    input       fin,
    output      fout,
    output      locked,
    input       fin_en,
    input[7:0] dly
);
reg[31:0] phase_p;
reg[31:0] phase_n;

wire[7:0] dly_cycle;
assign dly_cycle = {1'b0, dly[7:1]};

assign fout = fin_en ? (dly[0] ? (phase_n >> dly_cycle) : (phase_p >> dly_cycle)) : fin;

reg locked_p;
reg locked_n;
assign locked = dly[0] ? locked_n : locked_p;


reg[6:0] p_locked_counter; 
reg[6:0] n_locked_counter; 
always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
        locked_p <= 0;
        p_locked_counter <= 0;
        phase_p <= 0;
    end else begin
        if (fin_en == 1) begin
            if (locked) begin
                p_locked_counter <= p_locked_counter;
            end else begin
                p_locked_counter <= p_locked_counter + 1;
                if (p_locked_counter == dly_cycle) begin
                    locked_p <= 1;
                end else begin
                    locked_p <= 0;
                end
            end
            phase_p <= {phase_p[30:0], fin};
        end else begin
            locked_p <= 0;
            p_locked_counter <= 0;
            phase_p <= 0;
        end
    end
end

always @(negedge clk or negedge rst_n) begin
    if (!rst_n) begin
        locked_n <= 0;
        n_locked_counter <= 0;
        phase_n <= 0;
    end else begin
        if (fin_en == 1) begin
            if (locked) begin
                n_locked_counter <= n_locked_counter;
            end else begin
                n_locked_counter <= n_locked_counter + 1;
                if (n_locked_counter == dly_cycle) begin
                    locked_n <= 1;
                end else begin
                    locked_n <= 0;
                end
            end
            phase_n <= {phase_n[30:0], fin};
        end else begin
            locked_n <= 0;
            n_locked_counter <= 0;
            phase_n <= 0;
        end
    end
end

endmodule